﻿Imports System.IO

Public Class CsvReader

    Private _headerData As List(Of String)
    Private _data As List(Of List(Of String))

    Public ReadOnly Property Data As List(Of List(Of String))
        Get

            Return _data

        End Get
    End Property

    Public Sub New(ByVal path As String)

        _headerData = New List(Of String)
        _data = New List(Of List(Of String))

        If IO.File.Exists(path) Then

            Dim reader As New StreamReader(path)

            'handle header
            If reader.Peek <> -1 Then

                Dim line As String = reader.ReadLine()
                HandleParse(line, _headerData)

            End If

            'handle all data rows
            While Not String.IsNullOrEmpty(reader.Peek) AndAlso reader.Peek <> -1

                Dim newLine As New List(Of String)

                HandleParse(reader.ReadLine(), newLine)

                _data.Add(newLine)

            End While
            reader.Dispose()
        Else
            MessageBox.Show(String.Format("file not found @ {0}", path), "BattleAxePursuit", MessageBoxButtons.OK)
        End If

    End Sub

    Private Sub HandleParse(ByVal line As String, ByRef blockToWriteTo As List(Of String))

        'write all fields ending in comma
        While line.Contains(",")

            Dim nextSegment As String = line.Substring(0, line.IndexOf(","))
            blockToWriteTo.Add(nextSegment)
            line = line.Remove(0, nextSegment.Length + 1)
        End While

        'write final field - even if line is an empty string - Matt
        'If Not String.IsNullOrEmpty(line) Then
        blockToWriteTo.Add(line)
        'End If

    End Sub

End Class
